#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopip/djangoproject/include', '/opt/coopip/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject
from djangoproject import settings
setup_environ(settings)
from models import *
#********************Setup psycopg2 and django section********************

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings
import COOPIP_Misc
import djangoproject.models.ipbase
import COOPIP_Form, COOPIP_FormGeneral, COOPIP_FormRevenueProtection, COOPIP_FormIntranet, COOPIP_FormNetworkDevice
import reportlab
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import mm
from reportlab.graphics.barcode import code128
import CIS, GIS

def BuildSSNSearchForm():
    from django.contrib import admin
    Dict={}
    Dict['MemberNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'20'}))
    return Dict

def ProcessSSNSearchForm(form):
    import models
    MemberNumber=COOPIP_Form.FormGetString(form, 'MemberNumber')
    return MemberNumber

def PopulateSSNSearchForm(form):
    return form







def GenerateBarCodePDF(Numbers, FileName, APIndicator=False):

    c = canvas.Canvas(FileName, pagesize=(180, 90)) #Pagesize is in points, 1 point = 1/72 of an inch 2" X 1.5" labels
    if(APIndicator):
        for number in Numbers:
            barcode=code128.Code128('$' + number[0], barWidth=0.206*mm, barHeight=9*mm)  #Vendor, On Top
            barcode.drawOn(c, 8*mm, 23*mm)
            c.drawString(15*mm, 18*mm, '$' + number[0])

            barcode=code128.Code128('~' + number[1], barWidth=0.206*mm, barHeight=9*mm) #Invoice, On Bottom
            barcode.drawOn(c, 8*mm, 7*mm)
            c.drawString(15*mm, 2*mm, '~' + number[1])
            c.showPage()
            c.save()


        return


    for number in Numbers:
        barcode=code128.Code128('$' + number, barWidth=0.207*mm, barHeight=9*mm)  #WO
        barcode.drawOn(c, 9*mm, 21*mm)
        c.drawString(15*mm, 15*mm, '$' + number)
        c.showPage()
        

    c.save()




def BuildCISReportBarcodeForm():
    Dict={}
    Dict['MonthToPrint']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['YearToPrint']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['WONumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['APVendor']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    Dict['APInvoice']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
    return Dict

def ProcessCISReportBarcodeForm(form, Username):
    MonthToPrint=str(COOPIP_Form.FormGetInteger(form, 'MonthToPrint'))
    YearToPrint=str(COOPIP_Form.FormGetInteger(form, 'YearToPrint'))
    Now=datetime.datetime.now()
    try:
        Year = int(YearToPrint)
    except:
        Year = 0
    if(not Year):
        if(Now.month > MonthToPrint): #If month is a greater number, print the results from the previous year
            Year = Now.year - 1
        else:  #For current or previous months this year
            Year = Now.year

    if(MonthToPrint and not MonthToPrint == '0' and len(MonthToPrint) < 3):
        if(len(MonthToPrint) == 1):
            Month = '0' + MonthToPrint
        else:
            Month = MonthToPrint
        StartInteger = int(str(Year)[2:] + str(Month) + '00')  #CIS stores date values in an integer in the format YYMMDD in the jobdetl table
        EndInteger = int(str(Year)[2:] + str(Month) + '31')
        Jobs=CIS.Jobdetl.objects.filter(plantdate__gte=StartInteger).filter(plantdate__lte=EndInteger).order_by('job')
        Numbers=[]
        for job in Jobs:
            Numbers.append(str(job.job))
        GenerateBarCodePDF(Numbers, djangoproject.settings.CISReportBarcodePDFLocation + Username + '_WOMonth.pdf')
    WONumber=str(COOPIP_Form.FormGetString(form, 'WONumber'))
    if(WONumber and not WONumber == '0'):
        GenerateBarCodePDF([WONumber], djangoproject.settings.CISReportBarcodePDFLocation + Username + '_WO.pdf')
    APVendor=str(COOPIP_Form.FormGetString(form, 'APVendor'))
    APInvoice=str(COOPIP_Form.FormGetString(form, 'APInvoice'))

    if(APVendor and not APVendor == '0'):
        GenerateBarCodePDF([[APVendor, APInvoice]], djangoproject.settings.CISReportBarcodePDFLocation + Username + '_AP.pdf', APIndicator=True)
    return None

def PopulateCISReportBarcodeForm(form):
    form.data['MonthToPrint'] = ''
    form.data['YearToPrint'] = ''
    form.data['WONumber'] = ''
    form.data['APVendor'] = ''
    form.data['APInvoice'] = ''

    return form



def BuildOutdoorLightingBillingPhaseTableForm(SpecialBuildFormDataDict):
    Dict={}
    for i in range(0, len(SpecialBuildFormDataDict['Conditions'])):
        Dict['UpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['id' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
        Dict['gisid' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'5', 'READONLY':'True'}))
        Dict['gisstationidentifier' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gistagnumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gispolecompatibleunitname' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gisoutdoorlightmemberdescription' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25', 'READONLY':'True'}))
        Dict['gisoutdoorlightmapnumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gisoutdoorlightmeternumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gisoutdoorlightmetermapnumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gisoutdoorlightidleindicator' + str(i)] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
        Dict['gisneedsretirementindicator' + str(i)] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
        Dict['gisoutdoorlightratename' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'55', 'READONLY':'True'}))
        Dict['gisoutdoorlightcustomerownspoleindicator' + str(i)] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
        Dict['gisoutdoorlightcustomerownslightindicator' + str(i)] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'READONLY':'True'}))
        Dict['gisoutdoorlightadditionalbillingpolecount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12', 'READONLY':'True'}))
        Dict['giscreatedatetime' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25', 'READONLY':'True'}))
        Dict['giscreateusername' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12', 'READONLY':'True'}))
        Dict['giscircuitnumbers' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gisoutdoorlightconsumerownedlightcount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7', 'READONLY':'True'}))
        Dict['gissubstation' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['cismeterdistrict' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['cismetertaxdistrict' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['cismetercountycode' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['cismetercycle' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['cismemberseperator' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10', 'READONLY':'True'}))
        Dict['cislocation' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12', 'READONLY':'True'}))
        Dict['CISLocationSetupCompleteIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['LightsOriginallyInCIS' + str(i)] =forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
        Dict['LightsFinallyInCIS' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
        Dict['CISMemberSeparatorSetupCompleteIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['BillingSetupCompleteIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['DeleteIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['BillingSetupCompleteDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'25', 'READONLY':'True'}))
        Dict['BillingSetupCompleteUsername' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'12', 'READONLY':'True'}))
        Dict['SendRetirementToGISIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['SendToGISIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['Coopgisconditionmemberdescriptionhistory' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': '4', 'cols': '50'}))
    return Dict

def ProcessOutdoorLightingBillingPhaseTableForm(form, Username):
    i = 0
    while(True):
        
        if(not form.data.has_key('id' + str(i))):
            break
        UpdateIndicator=COOPIP_Form.FormGetBoolean(form, 'UpdateIndicator' + str(i))
        if(UpdateIndicator):
            
            outdoorLightingConversion=COOPIP_Form.FormGetObjectFromid(form, 'id' + str(i), djangoproject.models.ipbase.OutdoorLightingConversion)
            outdoorLightingConversion.DeleteIndicator=COOPIP_Form.FormGetBoolean(form, 'DeleteIndicator' + str(i))
            outdoorLightingConversion.CISLocationSetupCompleteIndicator=COOPIP_Form.FormGetBoolean(form, 'CISLocationSetupCompleteIndicator' + str(i))
            outdoorLightingConversion.CISMemberSeparatorSetupCompleteIndicator=COOPIP_Form.FormGetBoolean(form, 'CISMemberSeparatorSetupCompleteIndicator' + str(i))
            outdoorLightingConversion.LightsOriginallyInCIS=COOPIP_Form.FormGetInteger(form, 'LightsOriginallyInCIS' + str(i))
            outdoorLightingConversion.LightsFinallyInCIS=COOPIP_Form.FormGetInteger(form, 'LightsFinallyInCIS' + str(i))
            #raise(Exception(outdoorLightingConversion.LightsFinallyInCIS))
            formBillingSetupCompleteIndicator=COOPIP_Form.FormGetBoolean(form, 'BillingSetupCompleteIndicator' + str(i))
            if(not outdoorLightingConversion.BillingSetupCompleteIndicator) and formBillingSetupCompleteIndicator:
                outdoorLightingConversion.BillingSetupCompleteIndicator=True
                outdoorLightingConversion.BillingSetupCompleteDateTime=datetime.datetime.now()
                outdoorLightingConversion.BillingSetupCompleteUsername=Username
            #FIXME, Edit the GIS.Coopgisconditionmemberdescriptionhistory object if the username is the same, otherwise create a new one
            PotentialCoopgisconditionmemberdescriptionhistoryToEdit = GIS.Coopgisconditionmemberdescriptionhistory.objects.filter(condition__id=COOPIP_Form.FormGetInteger(form, 'gisid' + str(i))).order_by('-id')
            if(PotentialCoopgisconditionmemberdescriptionhistoryToEdit and PotentialCoopgisconditionmemberdescriptionhistoryToEdit[0].createusername==Username):
                CoopgisconditionmemberdescriptionhistoryToEdit = PotentialCoopgisconditionmemberdescriptionhistoryToEdit[0]
            else:
                CoopgisconditionmemberdescriptionhistoryToEdit = GIS.Coopgisconditionmemberdescriptionhistory()
                CoopgisconditionmemberdescriptionhistoryToEdit.id = GIS.Coopgisconditionmemberdescriptionhistory.objects.all().order_by('-id')[0].id + 1
                CoopgisconditionmemberdescriptionhistoryToEdit.condition = GIS.Coopgiscondition.objects.filter(id=COOPIP_Form.FormGetInteger(form, 'gisid' + str(i)))[0]
                CoopgisconditionmemberdescriptionhistoryToEdit.createusername = Username
                CoopgisconditionmemberdescriptionhistoryToEdit.createdatetime=datetime.datetime.now()
                CoopgisconditionmemberdescriptionhistoryToEdit.residesonserverindicator=True
            if(COOPIP_Form.FormGetString(form, 'Coopgisconditionmemberdescriptionhistory' + str(i))):
                CoopgisconditionmemberdescriptionhistoryToEdit.description = COOPIP_Form.FormGetString(form, 'Coopgisconditionmemberdescriptionhistory' + str(i))
                CoopgisconditionmemberdescriptionhistoryToEdit.save()


            
            SendRetirementToGISIndicator=COOPIP_Form.FormGetBoolean(form, 'SendRetirementToGISIndicator' + str(i))
            if(SendRetirementToGISIndicator and not outdoorLightingConversion.SendRetirementToGISIndicator):
                outdoorLightingConversion.SendRetirementToGISIndicator = True
                try:
                    GISCondition=GIS.Coopgiscondition.objects.filter(id=outdoorLightingConversion.gisid)[0]
                    GISCondition.retirementindicatormodifyusername = Username
                    GISCondition.retirementindicatormodifydatetime = datetime.datetime.now()
                    GISCondition.needsretirementindicator = True
                    GISCondition.save()
                except KeyError:
                    pass
            outdoorLightingConversion.SendRetirementToGISIndicator = SendRetirementToGISIndicator
            SendToGISIndicator=COOPIP_Form.FormGetBoolean(form, 'SendToGISIndicator' + str(i))
            if(SendToGISIndicator or SendRetirementToGISIndicator):
                outdoorLightingConversion.OutdoorLightBillingPhaseIndicator=False
                outdoorLightingConversion.OutdoorLightGISPhaseIndicator=True
                try:
                    GISCondition=GIS.Coopgiscondition.objects.filter(id=outdoorLightingConversion.gisid)[0]
                    GISCondition.outdoorlightsendbacktobillingphaseindicator=False
                    GISCondition.outdoorlightgisphaseindicator=True
                    GISCondition.save()
                except KeyError:
                    pass               
            outdoorLightingConversion.save()
        i = i + 1  #Next Form Field


def GetCoopgisconditionmemberdescriptionhistoryLatestNote(condition, Username=None):
    coopgisconditionmemberdescriptionhistory = GIS.Coopgisconditionmemberdescriptionhistory.objects.filter(condition__id=condition.gisid).order_by('-id')
    if(coopgisconditionmemberdescriptionhistory and coopgisconditionmemberdescriptionhistory[0].createusername == Username):
        return coopgisconditionmemberdescriptionhistory[0].description
    else:
        return ''



def PopulateOutdoorLightingBillingPhaseTableForm(form, Conditions, Username):
    for i in range(0, len(Conditions)):
        form.data['UpdateIndicator' + str(i)]=False
        form.setData({'id' + str(i): Conditions[i].id})
        form.setData({'gisid' + str(i): Conditions[i].gisid})

        form.setData({'gisstationidentifier' + str(i): Conditions[i].gisstationidentifier})
        form.setData({'gistagnumber' + str(i): Conditions[i].gistagnumber})
        form.setData({'gispolecompatibleunitname' + str(i): Conditions[i].gispolecompatibleunitname})

        form.setData({'gisoutdoorlightmemberdescription' + str(i): Conditions[i].gisoutdoorlightmemberdescription})
        form.setData({'gisoutdoorlightmapnumber' + str(i): Conditions[i].gisoutdoorlightmapnumber})
        form.setData({'gisoutdoorlightmeternumber' + str(i): Conditions[i].gisoutdoorlightmeternumber})
        form.setData({'gisoutdoorlightmetermapnumber' + str(i): Conditions[i].gisoutdoorlightmetermapnumber})
        form.setData({'gisoutdoorlightidleindicator' + str(i): Conditions[i].gisoutdoorlightidleindicator})
        form.setData({'gisneedsretirementindicator' + str(i): Conditions[i].gisneedsretirementindicator})
        form.setData({'gisoutdoorlightratename' + str(i): Conditions[i].gisoutdoorlightratename})
        form.setData({'gisoutdoorlightcustomerownspoleindicator' + str(i): Conditions[i].gisoutdoorlightcustomerownspoleindicator})
        form.setData({'gisoutdoorlightcustomerownslightindicator' + str(i): Conditions[i].gisoutdoorlightcustomerownslightindicator})
        form.setData({'giscreatedatetime' + str(i): Conditions[i].giscreatedatetime})
        form.setData({'giscreateusername' + str(i): Conditions[i].giscreateusername})
        form.setData({'giscircuitnumbers' + str(i): Conditions[i].giscircuitnumbers})
        form.setData({'gisoutdoorlightconsumerownedlightcount' + str(i): Conditions[i].gisoutdoorlightconsumerownedlightcount})
        form.setData({'gissubstation' + str(i): Conditions[i].gissubstation})
        form.setData({'gisoutdoorlightadditionalbillingpolecount' + str(i): Conditions[i].gisoutdoorlightadditionalbillingpolecount})
        form.setData({'cismeterdistrict' + str(i): Conditions[i].cismeterdistrict})
        form.setData({'cismetertaxdistrict' + str(i): Conditions[i].cismetertaxdistrict})
        form.setData({'cismetercountycode' + str(i): Conditions[i].cismetercountycode})
        form.setData({'cismetercycle' + str(i): Conditions[i].cismetercycle})
        form.setData({'cismemberseperator' + str(i): Conditions[i].cismemberseperator})
        form.setData({'cislocation' + str(i): Conditions[i].cislocation})
        form.setData({'CISLocationSetupCompleteIndicator' + str(i): Conditions[i].CISLocationSetupCompleteIndicator})
        form.setData({'LightsOriginallyInCIS' + str(i): Conditions[i].LightsOriginallyInCIS})
        form.setData({'LightsFinallyInCIS' + str(i):  Conditions[i].LightsFinallyInCIS})
        form.setData({'CISMemberSeparatorSetupCompleteIndicator' + str(i): Conditions[i].CISMemberSeparatorSetupCompleteIndicator})
        form.setData({'BillingSetupCompleteIndicator' + str(i): Conditions[i].BillingSetupCompleteIndicator})
        form.setData({'BillingSetupCompleteDateTime' + str(i): Conditions[i].BillingSetupCompleteDateTime})
        form.setData({'BillingSetupCompleteUsername' + str(i): Conditions[i].BillingSetupCompleteUsername})
        form.setData({'SendRetirementToGISIndicator' + str(i): Conditions[i].SendRetirementToGISIndicator})
        coopgisconditionmemberdescriptionhistoryString=GetCoopgisconditionmemberdescriptionhistoryLatestNote(Conditions[i], Username)
        form.setData({'Coopgisconditionmemberdescriptionhistory' + str(i): coopgisconditionmemberdescriptionhistoryString})  
        form.setData({'DeleteIndicator' + str(i): False})
        form.setData({'SendToGISIndicator' + str(i): False})
    return form






